{% extends "member/layout.html" %}

{% block title %}{{ task.name }}{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <!-- 任务标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h3 class="fw-bold text-primary mb-1">
                    <i class="fas fa-tasks me-2"></i>{{ task.name }}
                </h3>
                <p class="text-muted mb-0">{{ task.stage.project.name }} - {{ task.stage.name }}</p>
            </div>
            <div>
                <span class="badge status-badge bg-{{
                    'warning' if task.status == 'pending'
                    else 'info' if task.status == 'in_progress'
                    else 'success'
                }} bg-opacity-10 text-{{
                    'warning' if task.status == 'pending'
                    else 'info' if task.status == 'in_progress'
                    else 'success'
                }} border border-{{
                    'warning' if task.status == 'pending'
                    else 'info' if task.status == 'in_progress'
                    else 'success'
                }} border-opacity-25 rounded-pill px-3 py-2">
                    {{ task.status_label }}
                </span>
            </div>
        </div>

        <!-- 任务详情卡片 -->
        <div class="card dashboard-card border-0 mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="fw-bold text-muted mb-3">基本信息</h6>
                        <div class="info-list">
                            <div class="info-item d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">负责人</span>
                                <span class="fw-medium">{{ task.assignee.name if task.assignee else '未分配' }}</span>
                            </div>
                            <div class="info-item d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">创建时间</span>
                                <span class="fw-medium">{{ task.stage.project.created_at.strftime('%Y-%m-%d %H:%M') }}</span>
                            </div>
                            <div class="info-item d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">截止日期</span>
                                <span class="fw-medium">{{ task.due_date.strftime('%Y-%m-%d') if task.due_date else '未设置' }}</span>
                            </div>
                            <div class="info-item d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">优先级</span>

                                 <span class="badge {% if task.priority == 'low' %}bg-success{% elif task.priority == 'medium' %}bg-warning{% else %}bg-danger{% endif %}"
                                              id="previewPriority">
                                            {% if task.priority == 'low' %}低优先级
                                            {% elif task.priority == 'medium' %}中优先级
                                            {% else %}高优先级{% endif %}
                                        </span>
                            </div>
                            <div class="info-item d-flex justify-content-between py-2 border-bottom">
                                <span class="text-muted">当前进度</span>
                                <div class="d-flex align-items-center">
                                    <div class="progress me-2" style="width: 100px; height: 6px;">
                                        <div class="progress-bar bg-success" role="progressbar"
                                             style="width: {{ task.progress or 0 }}%"
                                             aria-valuenow="{{ task.progress or 0 }}"
                                             aria-valuemin="0"
                                             aria-valuemax="100">
                                        </div>
                                    </div>
                                    <span class="fw-medium">{{ task.progress or 0 }}%</span>
                                </div>
                            </div>

                            {% if task.status == 'completed' and task.rating %}
                            <div class="info-item d-flex justify-content-between py-2">
                                <span class="text-muted">任务评价</span>
                                <div class="d-flex align-items-center">
                                    <div class="text-warning me-2">
                                        {% for i in range(1, 6) %}
                                            <i class="fas fa-star{% if i > task.rating %}-o{% else %}{% endif %}"></i>
                                        {% endfor %}
                                    </div>
                                    {% if task.feedback %}
                                    <span class="fw-medium">{{ task.feedback }}</span>
                                    {% endif %}
                                </div>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6 class="fw-bold text-muted mb-3">任务描述</h6>
                        <div class="p-3 bg-light rounded">
                            {{ task.description if task.description else '暂无详细描述' }}
                        </div>
                    </div>
                </div>

                <!-- 附件区域 -->
                <div class="mt-4 pt-3 border-top">
                    <h6 class="fw-bold text-muted mb-3">任务附件</h6>
                    {% if task.attachments %}
                    <div class="list-group mb-3">
                        {% for attachment in task.attachments %}
                        <div class="list-group-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="fas fa-paperclip me-2"></i>
                                    <a href="{{ url_for('member.task.download_attachment', attachment_id=attachment.id) }}" class="text-decoration-none">
                                        {{ attachment.filename }}
                                    </a>
                                    <small class="text-muted ms-2">{{ attachment.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
                                </div>
                                {% if attachment.uploader_id == current_member.id or task.stage.project.owner_id == current_member.id %}
                                <button class="btn btn-sm btn-outline-danger delete-attachment"
                                    data-attachment-id="{{ attachment.id }}"
                                    data-csrf-token="{{ csrf_token() }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <script>
                                document.querySelector('.delete-attachment').addEventListener('click', function() {
                                    const attachmentId = this.dataset.attachmentId;
                                    const csrfToken = this.dataset.csrfToken;

                                    if (confirm('确定要删除此附件吗？')) {
                                        fetch(`/member/task/attachment/${attachmentId}/delete`, {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/json',
                                                'X-CSRFToken': csrfToken
                                            },
                                            body: JSON.stringify({})
                                        })
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.success) {
                                                // 删除成功后刷新附件列表
                                                location.reload();
                                            } else {
                                                alert(data.message);
                                            }
                                        })
                                        .catch(error => {
                                            console.error('Error:', error);
                                            alert('删除失败');
                                        });
                                    }
                                });
                                </script>
                                <script>
                                function confirmAttachmentDelete(button, attachmentId) {
                                    if (!confirm('确定要删除此附件吗？')) {
                                        return false;
                                    }
                                    // 检查附件是否存在
                                    fetch(`/member/task/attachment/${attachmentId}/check`)
                                        .then(response => {
                                            if (!response.ok) {
                                                alert('附件不存在或已被删除');
                                                return false;
                                            }
                                            return true;
                                        })
                                        .catch(() => {
                                            alert('检查附件状态失败');
                                            return false;
                                        });
                                    return true;
                                }
                                </script>
                                {% endif %}
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <p class="text-muted">暂无附件</p>
                    {% endif %}

                    {% if task.assignee_id == current_member.id or task.stage.project.owner_id == current_member.id %}
                    <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#uploadModal">
                        <i class="fas fa-plus me-1"></i>添加附件
                    </button>
                    {% endif %}
                </div>

                <!-- 操作按钮 -->
                <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
                    <a href="{{ url_for('member.jira.project_detail', project_id=task.stage.project.id) }}"
                       class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i>返回项目
                    </a>

                    <div class="d-flex gap-2">
                        {% if task.stage.project.owner_id == current_member.id and task.status == 'todo' %}
                        <a href="{{ url_for('member.task.edit', task_id=task.id) }}" class="btn btn-outline-primary">
                            <i class="fas fa-edit me-2"></i>编辑任务
                        </a>
                        {% endif %}

                        {% if task.status == 'pending_acceptance' and task.assignee_id == current_member.id %}
                        <form method="post" action="{{ url_for('member.task.start', task_id=task.id) }}" class="d-inline">
                            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-play me-2"></i>开始任务
                            </button>
                        </form>
                        {% endif %}

                        {% if task.status == 'in_progress' and task.assignee_id == current_member.id %}
                        <form method="post" action="{{ url_for('member.task.update_progress', task_id=task.id) }}" class="d-inline">
                            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                            <div class="input-group">
                                <input type="number" name="progress" class="form-control"
                                       min="0" max="100" value="{{ task.progress or 0 }}"
                                       placeholder="进度百分比">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-sync-alt me-2"></i>更新进度
                                </button>
                            </div>
                        </form>
                        {% endif %}

                        {% if task.status != 'completed' and task.assignee_id == current_member.id %}
                        <form method="post" action="{{ url_for('member.task.complete', task_id=task.id) }}" class="d-inline">
                            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                            <input type="hidden" name="project_id" value="{{ task.stage.project.id }}">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-check-circle me-2"></i>标记完成
                            </button>
                        </form>
                        {% endif %}
                    </div>
                </div>

                <!-- 任务评价部分 -->
                {% if task.status == 'completed' and task.stage.project.owner_id == current_member.id %}
                <div class="mt-4 pt-3 border-top">
                    <h6 class="fw-bold text-muted mb-3">任务评价</h6>
                    <form method="post" action="{{ url_for('member.task.rate', task_id=task.id) }}">
                        <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                        <input type="hidden" name="project_id" value="{{ task.stage.project.id }}">

                        <div class="mb-3">
                            <label class="form-label">评分 (1-5星)</label>
                            <div class="rating-group">
                                {% for i in range(1, 6) %}
                                <!-- 注意：这里使用6-i来反转评分值，因为CSS样式是反向显示的 -->
                                <input type="radio" id="star{{i}}" name="rating" value="{{6-i}}"
                                       {% if task.rating == 6-i %}checked{% endif %}>
                                <label for="star{{i}}"><i class="fas fa-star"></i></label>
                                {% endfor %}
                            </div>
                            <small class="form-text text-muted">1星表示非常不满意，5星表示非常满意</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">评价反馈</label>
                            <textarea name="feedback" class="form-control" rows="3">{{ task.feedback or '' }}</textarea>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-star me-2"></i>提交评价
                        </button>
                    </form>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<style>
.rating-group {
    display: inline-flex;
    flex-direction: row-reverse;
}
.rating-group input {
    display: none;
}
.rating-group label {
    color: #ddd;
    cursor: pointer;
    font-size: 1.5rem;
    padding: 0 0.2rem;
}
.rating-group input:checked ~ label,
.rating-group input:hover ~ label {
    color: gold;
}
.rating-group input:checked ~ label:hover,
.rating-group input:hover ~ label:hover {
    color: gold;
}
</style>

<style>
.status-badge {
    font-weight: 500;
    font-size: 0.9rem;
}

.info-list .info-item {
    transition: all 0.2s;
}

.info-list .info-item:hover {
    background-color: #f8f9fa;
}
</style>
<!-- 附件上传模态框 -->
<div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">上传任务附件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form method="post" action="{{ url_for('member.task.upload_attachment', task_id=task.id) }}" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <div class="mb-3">
                        <label for="fileInput" class="form-label">选择文件</label>
                        <input class="form-control" type="file" id="fileInput" name="file" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">描述（可选）</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-upload me-1"></i>上传
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}